package org.luxor.commons.security.config;

import org.luxor.commons.openfeign.config.DefaultFeignAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.AnyNestedCondition;
import org.springframework.boot.autoconfigure.condition.ConditionalOnNotWebApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.security.oauth2.OAuth2ClientProperties;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client;

/**
 * OAuth2 client_credentials 客户端应用配置器
 *
 * @author Mr.Yan  @date: 2020/10/13
 */
@Configuration
@EnableOAuth2Client
@Conditional(OAuth2ClientServerAutoConfiguration.ClientCredentialsCondition.class)
@Import({DefaultFeignAutoConfiguration.class, TokenRelayAutoConfiguration.class})
public class OAuth2ClientServerAutoConfiguration {

    private final OAuth2ClientProperties credentials;

    public OAuth2ClientServerAutoConfiguration(OAuth2ClientProperties credentials) {
        this.credentials = credentials;
    }


    /**
     * Condition to check for client credentials.
     */
    static class ClientCredentialsCondition extends AnyNestedCondition {

        ClientCredentialsCondition() {
            super(ConfigurationPhase.PARSE_CONFIGURATION);
        }

        @ConditionalOnProperty(prefix = "security.oauth2.client", name = "grant-type", havingValue = "client_credentials", matchIfMissing = false)
        static class ClientCredentialsConfigured {
        }

        @ConditionalOnNotWebApplication
        static class NoWebApplication {
        }

    }
}
